<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use App\Models\User;

class TranslateSection extends Model
{
    CONST NOT_TRANSLATED = false;
    CONST IS_TRANSLATED = true;

    CONST TYPE_FIRST_TRANSLATE = 1;
    CONST TYPE_AGAIN_TRANSLATE = 2;
    CONST TYPE_IMPROVED_TRANSLATE = 3;
    protected $fillable = [
        'original_text',
        'original_text_html',
        'translate_text',
        'translate_text_html',
        'translate_record_id',
        'is_translated',
        'translator_ids',
        'locked_date',
    ];

    public $timestamps = true;

    public function translators()
    {
        $user_ids = explode('-',$this->translator_ids);
        $users = null;
        if($user_ids)
        {
            $users = User::whereIn('id', $user_ids)->get();
        }
        return $users;
    }

    public function translatorIds()
    {
        $user_ids = explode('-',$this->translator_ids);

        return $user_ids;
    }

    public function improvedUserIds()
    {
        $transRecords = $this->translateRecords;
        $improved_user_ids_arr = [];
        foreach ($transRecords AS $record)
        {
            $improved_user_ids_arr = array_merge($improved_user_ids_arr, $record->improvedUserIds());
        }

        return array_unique($improved_user_ids_arr);
    }

    public function translateRecords()
    {
        return $this->hasMany(TranslateRecord::class, 'translate_section_id', 'id');
    }

    public function appliedTransRecord()
    {
        return $this->hasOne(TranslateRecord::class, 'id', 'translate_record_id');
    }

    public function isTranslated()
    {
        return $this->attributes['is_translated'] == self::IS_TRANSLATED;
    }

    public function isCanEdit()
    {
        return $this->attributes['locked_date'] < date('Y-m-d h:i:s', time());
    }

    public function setLockedDateAttribute($value)
    {
        $this->attributes['locked_date'] = date('Y-m-d h:i:s', strtotime("+{$value} hours"));
    }

    public function setAttributes($attrs)
    {
        return self::update($attrs);
    }

    public function getAttrbute($attr_name)
    {
        return $this->attributes[$attr_name];
    }

    public function getWaitReviewCount()
    {
        $this->translateRecord()->getBaseQuery()->count('id');
    }

    public function translateTimeAttribute($value)
    {
        return Carbon::createFromTimeString($value)->diffForHumans();
    }

    public function topic()
    {
        return $this->belongsTo(Topic::class, 'topic_id', 'id');
    }

}
